package com.atguigu.lease.web.app.service.impl;

import com.atguigu.lease.model.entity.BrowsingHistory;
import com.atguigu.lease.web.app.mapper.BrowsingHistoryMapper;
import com.atguigu.lease.web.app.service.BrowsingHistoryService;
import com.atguigu.lease.web.app.vo.history.HistoryItemVo;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

/**
 * @author liubo
 * @description 针对表【browsing_history(浏览历史)】的数据库操作Service实现
 * @createDate 2023-07-26 11:12:39
 */
@Service
@Slf4j
public class BrowsingHistoryServiceImpl extends ServiceImpl<BrowsingHistoryMapper, BrowsingHistory>
        implements BrowsingHistoryService {

    @Autowired
    private BrowsingHistoryMapper browsingHistoryMapper;

    /**
     * @author gengjian
     * @date 2024/12/15 19:40:46
     * 获取浏览历史记录vo
     */
    @Override
    public void pageHistoryItemVo(IPage<HistoryItemVo> page,Long userId) {
        browsingHistoryMapper.pageHistoryItemVo(page,userId);
    }

    /**
     * @author gengjian
     * @date 2024/12/15 22:51:13
     * 保存浏览历史记录
     */
    @Async
    @Override
    public void saveHistory(Long userId, Long room_id) {
        //创建浏览记录
        BrowsingHistory browsingHistory = new BrowsingHistory();
        browsingHistory.setBrowseTime(new Date());
        browsingHistory.setRoomId(room_id);
        browsingHistory.setUserId(userId);
        //如果相同用户看了相同房间则覆盖 否则新增
        LambdaQueryWrapper<BrowsingHistory> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(BrowsingHistory::getUserId,userId);
        queryWrapper.eq(BrowsingHistory::getRoomId,room_id);
        Long count = super.count(queryWrapper);
        if (count > 0){
            LambdaUpdateWrapper<BrowsingHistory> updateWrapper = new LambdaUpdateWrapper<>();
            updateWrapper.eq(BrowsingHistory::getUserId,userId);
            updateWrapper.eq(BrowsingHistory::getRoomId,room_id);
            super.update(browsingHistory,updateWrapper);
        }else {
            super.save(browsingHistory);
        }
    }
}




